
import { getPermission } from '@/api/login';
import Vue from 'vue'
const permission = {
    state: {
        routers: [],
        addRouters: []
    },
    // mutations: {
    //     SET_ROUTERS: (state, routers) => {
    //         state.addRouters = routers
    //         state.routers = constantRouterMap.concat(routers)
    //     }
    // },
    actions: {
        getRouter({
            commit
        }, data) {
            return new Promise(async resolve => {
                const dt = await getPermission()
                // sessionStorage.setItem('permission', JSON.stringify(dt.data))
                Vue.prototype.resetSetItem("permission", JSON.stringify(dt.data));
                filterAsyncRoutes(Vue.prototype.$router, dt.data)
            })
        }
    }
}


function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role));
    }
    return true;
}
export function filterAsyncRoutes(routes, roles) {
    const res = [];
    // 遍历父级
    routes.forEach(route => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            // 判断是否有子路由，根据roles进行递归处理
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles);
            }
            res.push(tmp);
        }
    });

    return res;
}

export default permission